import {  ref,watchEffect } from 'vue'

import { KeyCode } from '@/utils/constants'

/**
 * 判断是否按下空格
 * @param keyDownCb 空格键按下回调
 * @param keyUpCb 空格键松开回调
 * @returns 空格键按下状态
 */
export function useSpaceEvent(
  keyDownCb?: (spacePressState: boolean) => void,
  keyUpCb?: (spacePressState: boolean) => void
) {
  // const [isPressSpace, setIsPressSpace] = useState<boolean>(false)
  const isPressSpace = ref(false);
  const setIsPressSpace = function(value:boolean){
    isPressSpace.value = value
  }
  const onKeydown = (e: KeyboardEvent) => {
    if (e.code === KeyCode.SPACE) {
      setIsPressSpace(true)
      keyDownCb?.(true)
    }
  }

  const onKeyup = (e: KeyboardEvent) => {
    if (e.code === KeyCode.SPACE) {
      setIsPressSpace(false)
      keyUpCb?.(false)
    }
  }
  watchEffect(() => {
    window.addEventListener('keydown', onKeydown)
    window.addEventListener('keyup', onKeyup)
  })

  return isPressSpace
}

/**
 * window resize hook
 * @param cb resize callback
 */
export function useResizeEvent(cb: () => void) {
  const onResize = () => {
    cb()
  }
  watchEffect(() => {
    window.addEventListener('resize', onResize)
  })

  
}

/**
 * 监听backspace键
 * @param keyDownCb backspace键按下回调
 */
export const useBackspace = (keyDownCb?: () => void) => {
  const onKeydown = (e: KeyboardEvent) => {
    if (e.code === KeyCode.BACKSPACE) {
      keyDownCb?.()
    }
  }
  watchEffect(() => {
    window.addEventListener('keydown', onKeydown)
  })

  
}
